package com.ruoyi.system.controller;

import java.util.Calendar;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;


/**
 * 项目管理Controller
 *
 * @author ruoyi
 * @date 2024-08-03
 */
@RestController
@RequestMapping("/system/project")
public class SysProjectController extends BaseController {
    @Autowired
    private ISysProjectService sysProjectService;

    @Autowired
    private ISysProjectTypeService sysProjectTypeService;

    @Autowired
    private ISysProjectTenderModeService sysProjectTenderModeService;

    @Autowired
    private ISysProjectBidevaluationProcessService sysProjectBidevaluationProcessService;

    @Autowired
    private ISysProjectBidevaluationModeService sysProjectBidevaluationModeService;

    @Autowired
    private ISysProjectFundingSourceService sysProjectFundingSourceService;

    @Autowired
    private ISysProjectPayerService sysProjectPayerService;

    @Autowired
    private ISysTendererService sysTendererService;

    @Autowired
    private ISysCompanyService sysCompanyService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysCompanyAreaService sysCompanyAreaService;

    @Autowired
    private ISysBidderService sysBidderService;

    /**
     * 查询项目管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysProject sysProject) {
        startPage();
        List<SysProject> list = sysProjectService.selectSysProjectList(sysProject);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:project:lists')")
    @GetMapping("/lists")
    public AjaxResult lists(SysProject sysProject) {
        System.out.println(sysProject);
        List<SysProject> list = sysProjectService.selectSysProjectList(sysProject);
        return success(list);
    }

    /**
     * 导出项目管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:export')")
    @Log(title = "项目管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysProject sysProject) {
        List<SysProject> list = sysProjectService.selectSysProjectList(sysProject);
        ExcelUtil<SysProject> util = new ExcelUtil<SysProject>(SysProject.class);
        util.exportExcel(response, list, "项目管理数据");
    }

    /**
     * 获取项目管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysProjectService.selectSysProjectById(id));
    }

    /**
     * 新增项目管理
     */
    @PreAuthorize("@ss.hasPermi('system:project:add')")
    @Log(title = "项目管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysProjectDTO sysProjectDTO) {

        int isProjectCode = sysProjectDTO.getIsProjectCode();
        if (isProjectCode == 2) {

            if (sysProjectDTO.getProjectTypeId() < 1) {
                return AjaxResult.error("请选择招标类型");
            }

            if (sysProjectDTO.getProjectTenderModeId() < 1) {
                return AjaxResult.error("招标方式");
            }

            SysProjectType projectType = sysProjectTypeService.selectSysProjectTypeById(sysProjectDTO.getProjectTypeId());
            SysProjectTenderMode projectTenderMode = sysProjectTenderModeService.selectSysProjectTenderModeById(sysProjectDTO.getProjectTenderModeId());

            // 生成项目号逻辑
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
            String total = Integer.toString(getNowMonthProjectTotal()+1);
            String projectCode = "JC" + dateFormat.format(new Date()) + projectType.getTag() + projectTenderMode.getTag() + total;
            sysProjectDTO.setProjectCode( projectCode);

        }
        //设置项目状态
        sysProjectDTO.setProjectStatus(1);

        return toAjax(sysProjectService.insertSysProject(sysProjectDTO));
    }

    /**
     * 获取当月项目总数
     * @return
     */
    public int getNowMonthProjectTotal() {
        // 获取当前日期和时间的日历实例
        Calendar calendar = Calendar.getInstance();

        // 获取当月的开始时间
        Calendar startCalendar = (Calendar) calendar.clone();
        startCalendar.set(Calendar.DAY_OF_MONTH, 1);
        startCalendar.set(Calendar.HOUR_OF_DAY, 0);
        startCalendar.set(Calendar.MINUTE, 0);
        startCalendar.set(Calendar.SECOND, 0);
        startCalendar.set(Calendar.MILLISECOND, 0);
        Date startDate = startCalendar.getTime();

        // 获取当月的结束时间
        Calendar endCalendar = (Calendar) calendar.clone();
        endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        endCalendar.set(Calendar.HOUR_OF_DAY, 23);
        endCalendar.set(Calendar.MINUTE, 59);
        endCalendar.set(Calendar.SECOND, 59);
        endCalendar.set(Calendar.MILLISECOND, 999);
        Date endDate = endCalendar.getTime();

        // 定义日期时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String startCreateTime = sdf.format(startDate);
        String endCreateTime = sdf.format(endDate);
        SysProject sysProject = new SysProject();
        sysProject.setStartCreateTime(startCreateTime);
        sysProject.setEndCreateTime(endCreateTime);
        List<SysProject>  projectList = sysProjectService.selectSysProjectList(sysProject);
        return projectList.size();
    }

    /**
     * 修改项目管理
     */
    @PreAuthorize("@ss.hasPermi('system:project:edit')")
    @Log(title = "项目管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysProject sysProject) {
        return toAjax(sysProjectService.updateSysProject(sysProject));
    }

    /**
     * 删除项目管理
     */
    @PreAuthorize("@ss.hasPermi('system:project:remove')")
    @Log(title = "项目管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysProjectService.deleteSysProjectByIds(ids));
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysProject> util = new ExcelUtil<SysProject>(SysProject.class);
        util.importTemplateExcel(response, "项目数据");
    }

    @Log(title = "项目管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:project:import')")
    @PostMapping("/importData")
    @Transactional
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysProject> util = new ExcelUtil<SysProject>(SysProject.class);
        List<SysProject> projectList = util.importExcel(file.getInputStream());

        try {
            for (SysProject data : projectList) {

                // (1) 匹配 招标类型Id
                if (data.getProjectTypeName() != null) {
                    SysProjectType projectTypeInfo = sysProjectTypeService.selectSysProjectTypeByName(data.getProjectTypeName());
                    if (projectTypeInfo != null) {
                        data.setProjectTypeId(projectTypeInfo.getId());
                    }
                }

                // (2) 匹配 招标方式Id
                if (data.getProjectTenderModeName() != null) {
                    SysProjectTenderMode projectTenderMode = sysProjectTenderModeService.selectSysProjectTenderModeByName(data.getProjectTenderModeName());
                    if (projectTenderMode != null) {
                        data.setProjectTenderModeId(projectTenderMode.getId());
                    }
                }

                // (3) 匹配 项目流程Id
                if (data.getProjectBidevaluationProcessName() != null) {
                    SysProjectBidevaluationProcess projectBidevaluationProcess = sysProjectBidevaluationProcessService.selectSysProjectBidevaluationProcessByName(data.getProjectBidevaluationProcessName());
                    if (projectBidevaluationProcess != null) {
                        data.setProjectBidevaluationProcessId(projectBidevaluationProcess.getId());
                    }
                }

                // (4) 匹配 评标方法ID
                if (data.getProjectBidevaluationModeName() != null) {
                    SysProjectBidevaluationMode projectBidevaluationMode = sysProjectBidevaluationModeService.selectSysProjectBidevaluationModeByName(data.getProjectBidevaluationModeName());
                    if (projectBidevaluationMode != null) {
                        data.setProjectBidevaluationModeId(projectBidevaluationMode.getId());
                    }
                }

                // (5) 匹配 资金来源ID
                if (data.getProjectFundingSourceName() != null) {
                    SysProjectFundingSource projectFundingSource = sysProjectFundingSourceService.selectSysProjectFundingSourceByName("混合资金");
                    if (projectFundingSource != null) {
                        data.setProjectFundingSourceId(projectFundingSource.getId());
                    }
                }

                // (6) 匹配 服务费付款方ID
                if (data.getProjectPayerName() != null) {
                    SysProjectPayer projectPayer = sysProjectPayerService.selectSysProjectPayerByName(data.getProjectPayerName());
                    if (projectPayer != null) {
                        data.setProjectPayerId(projectPayer.getId());
                    }
                }

                // (7) 收费类型
                if (data.getProjectPaymentTypeName() != null) {
                    if (data.getProjectPaymentTypeName() == "定额") {
                        data.setProjectPaymentTypeId(2);
                    } else {
                        data.setProjectPaymentTypeId(1);
                    }
                }

                // (8) 匹配 委托业主ID
                if (data.getProjectTenderee() != null) {
                    SysTenderer tenderer = sysTendererService.selectSysTendererByName(data.getProjectTenderee());
                    if (tenderer != null) {
                        data.setProjectTendereeId(tenderer.getId());
                    }
                }

                // (9) 匹配 资质主体ID
                if (data.getProjectAgencyName() != null) {
                    SysCompany projectAgency = sysCompanyService.selectSysCompanyByName(data.getProjectAgencyName());
                    if (projectAgency != null) {
                        data.setProjectAgencyId(Long.valueOf(projectAgency.getId()));
                    }
                }

                // (10) 匹配 项目开发人员ID
                if (data.getProjectDeveloper() != null) {
                    SysUser developerUser = sysUserService.selectUserByNickName(data.getProjectDeveloper());
                    if (developerUser != null) {
                        data.setProjectDeveloperId(developerUser.getUserId());
                    }
                }

                // (11) 匹配 项目执行人ID
                if (data.getProjectOperator() != null) {
                    SysUser operatorUser = sysUserService.selectUserByNickName(data.getProjectOperator());
                    if (operatorUser != null) {
                        data.setProjectOperatorId(operatorUser.getUserId());
                    }
                }

                // (12) 匹配 项目所属部门ID
                if (data.getProjectDeptName() != null) {
                    SysDept sysDept = sysDeptService.selectDeptByName(data.getProjectDeptName());
                    if (sysDept != null) {
                        data.setProjectDeptId(sysDept.getDeptId());
                    }
                }

                // (13) 匹配 项目负责人ID
                if (data.getProjectLeader() != null) {
                    SysUser leaderUser = sysUserService.selectUserByNickName(data.getProjectLeader());
                    if (leaderUser != null) {
                        data.setProjectLeaderId(leaderUser.getUserId());
                    }
                }

                // (14) 匹配 项目执行地区ID
                if (data.getProjectAreaName() != null) {
                    SysCompanyArea companyArea = sysCompanyAreaService.selectSysCompanyAreaByAreaName(data.getProjectAreaName());
                    if (companyArea != null) {
                        data.setProjectAreaId(companyArea.getAreaId());
                    }
                }

                // (15) 匹配 中标单位
                if (data.getProjectWinBidder() != null) {
                    SysBidder winBidder = sysBidderService.selectSysBidderByName(data.getProjectWinBidder());
                    if (winBidder != null) {
                        data.setProjectWinBidderId(Long.valueOf(winBidder.getId()));
                    }
                }

                if (data.getProjectCode() != null) {
                    SysProject projectParams = new SysProject();
                    projectParams.setProjectCode(data.getProjectCode());
                    SysProject projectResult = sysProjectService.selectSysProject(projectParams);
                    if (projectResult != null) throw new RuntimeException("项目编号" + data.getProjectCode() + "的项目已经存在！");
                }

                // 导入
                sysProjectService.insertSysProject(data);
            }

            return success("导入成功");
        } catch (Exception e) {
            // 出现异常，事务会自动回滚
            throw new RuntimeException("导入失败:" + e.getMessage(), e);
        }
    }
}
